package com.mls.guardian.appst.chain.excutor.Upgrade;

import com.mls.guardian.appst.chain.TaskExecutor;
import com.mls.guardian.appst.chain.TaskInvoker;
import com.mls.guardian.appst.chain.TaskResult;
import com.mls.guardian.appst.shell.ShellScriptExecutorFuture;
import com.mls.guardian.common.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * Created by root on 15-12-9.
 */
public class UnzipExcutor implements TaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(UnzipExcutor.class);

    @Override
    public TaskResult exec(TaskInvoker invoker) {
        String bashFilePath = System.getProperty("user.home") + File.separator + "guardianConfig" + File.separator + "guardian_" + System.currentTimeMillis() + ".sh";
        String gitAddress = invoker.getConfig().getGitAddress();
        String sourceDest = invoker.getConfig().getSourceDest();

        TaskResult result = null;
        try {
            log.info("----开始unzip----");
            Path sourcePath = Paths.get(sourceDest, "distributions", "Guardian-1.0.tgz");
            Path targetPath = Paths.get(Paths.get(sourceDest).getParent().toString(), "app", "Guardian-1.0.tgz");

            if (Files.exists(sourcePath)) {
                Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            } else {
                throw new Exception(sourcePath.toString() + "未找到文件");
            }

            FileUtil.append(bashFilePath, "cd " + targetPath.getParent().toString());
            FileUtil.append(bashFilePath, "tar -xvf Guardian-1.0.tgz");
            FileUtil.append(bashFilePath, "rm -rf Guardian-1.0.tgz");
            FileUtil.append(bashFilePath, "echo done");

            result = new ShellScriptExecutorFuture("sh " + bashFilePath).execute();

            //暂停一下
            int sleepSecond = invoker.getConfig().getRestartSleep();
            if (sleepSecond <= 0) {
                sleepSecond = 10;
            }
            try {
                Thread.sleep(sleepSecond * 1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            result = new TaskResult();
            result.setSuc(false);
            result.setError(e.getMessage());

            e.printStackTrace();
        } finally {
            try {
                Files.delete(Paths.get(bashFilePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("----结束unzip[{}]----", result.isSuc());
        }

        if (result.isSuc() == true) {
            return invoker.invoke();
        }

        return result;
    }
}
